//
//  MyCollectionTopicVC.swift
//  Venus
//
//  Created by qurongxiang on 2018/9/8.
//  Copyright © 2018年 zhaowang. All rights reserved.
//

import UIKit
import MJRefresh

class MyCollectionTopicVC: UIViewController {
    
    let tableView = UITableView.init(frame: CGRect.zero)
    var page : Int = 1
    var pageSize = 10
    var hasMore = true
    var topicAry = [TopicModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.green
        
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib.init(nibName: "TopicTableViewCell", bundle: nil), forCellReuseIdentifier: "TopicTableViewCell")
        self.loadData(refresh: true)
        tableView.mj_header =  MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self!.loadData(refresh: true)
        })
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self!.loadData(refresh: false)
        })
        tableView.tableFooterView = UIView.init(frame: CGRect.zero)
        
            
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
}
extension MyCollectionTopicVC : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.topicAry.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TopicTableViewCell", for: indexPath) as! TopicTableViewCell
        cell.configModel(model: topicAry[indexPath.item], index: indexPath)
        cell.selectionStyle = .none
        cell.deleteBlock = { [weak self] in
            let deleteConfirmVC =  TopicDeleteViewController()
            self?.navigationController?.pushViewController(deleteConfirmVC, animated: true)
            deleteConfirmVC.topicModel = (self?.topicAry[indexPath.row])!;
            deleteConfirmVC.deletedBlock = {(isSuccess) in
                if (isSuccess){
                    self?.topicAry.remove(at: indexPath.row )
                    self?.tableView.reloadData()
                }
            }
        }
        return cell
    }
}

extension MyCollectionTopicVC {
    @objc func loadData(refresh : Bool) {
        page = refresh ? 1 : page + 1
        let dict:Dictionary = [
            "timestamp":"2",
            "userId":String(UserInfo.shareInstance.userModel().id),
            "operatorId":String(UserInfo.shareInstance.userModel().id),
            "pageNo":String(format: "%d", page),
            "pageSize":"10",
            "sign":"2"
            ] as [String : Any]
        let string = dict.formatApi()
        NetworkTools.shareInstance.loadData(.post, URLString:kqueryMyCollectTopicList + string,parameters:dict) { [weak self] (data, failed) in
            if !failed {
                self!.hudHide()
                self!.tableView.mj_footer.endRefreshing()
                guard let resultDict = data as? [String : NSObject] else { return }
                guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
                let topicList = TopicModel.tmSpeelBreakModelArr(dataArray)
                if topicList.count != 0 {
                    if refresh {
                        self?.topicAry = topicList as! [TopicModel]
                        self?.tableView.mj_header.endRefreshing()
                    }else {
                        self!.topicAry.append(contentsOf: topicList as! [TopicModel])
                        self?.tableView.mj_footer.endRefreshing()
                    }
                    self!.hasMore = true
                    self?.tableView.reloadData()
                } else {
                    self?.hasMore = false
                    self?.tableView.mj_footer.endRefreshingWithNoMoreData();
                    self?.tableView.mj_header.endRefreshing()
                    self?.showEmptyDataView()
                }
                self?.tableView.reloadData()
            }else{
                self?.page = 1
                self?.topicAry.removeAll()
                self?.hasMore = false
                self?.tableView.mj_header.endRefreshing();
                self?.tableView.mj_footer.endRefreshing()
                self?.showNetworkErrorView(action: #selector(self?.loadData(refresh:)))
            }
        }
    }
}
